
// 获取轮播图列表数据
function loadSwiper() {
  $.ajax({
    type: 'GET',
    url: '/admin/swipers',
    success: function (res) {
      let str = '';
      console.log(res);
      res.data.forEach((data) => {
        let span = '';
        if (data.swiperstatus === 1) {
          span = `<span data-id='${data.id}' data-status='1' class='layui-badge layui-bg-green'>√</span>`
        } else {
          span = `<span data-id='${data.id}' data-status='2' class='layui-badge layui-bg-cyan'>×</span>`
        }
        str += `
        <tr>
        <td>${data.id}</td>
        <td>
          <img src="http://localhost:8888/uploads/${data.swiperimg}">
        </td>
        <td>${data.swiperimg}</td>
        <td>
         ${span}
        </td>
        <td>
          <button data-id="${data.id}" type="button" class="layui-btn layui-btn-xs layui-btn-danger del">
            删除
          </button>
        </td>
      </tr>
        
        `;
      })
      $('.layui-table tbody').html(str)
    }
  })
}
loadSwiper();


// 轮播图状态切换
$('.layui-table tbody').on('click', '.layui-badge', function (e) {
  let id = $(this).data('id');
  let status = $(e.target).data('status');
  console.log(id);
  if (status === 1) {
    status = 2;
  } else {
    status = 1;
  }
  console.log(status);
  $.ajax({
    type: 'PUT',
    url: `/admin/swipers/${id}`,
    data: {
      status: status,
    },
    success: function (res) {
      console.log(res);
      if (res.status === 0) {
        layer.msg(res.message);
        loadSwiper();
      }
    }
  })
})

// 删除操作
$(".layui-table tbody").on('click','.del',function(){
  let id = $(this).data('id');
  layer.confirm('是否删除该图？',function(index){
    $.ajax({
      type: 'DELETE',
      url: '/admin/swipers/' + id,
      success: function (res) {
        if (res.status === 0) {
          layer.close(index);
          loadSwiper();
        }
      }
    })
  })
})

// 上传轮播图按钮点击事件
$("#uploadSwiper").on('click',function(){
  $("#myfile").click()
})
// 监听文件选中事件
$("#myfile").on("change", function () {
  let list = this.files;
  let fd = new FormData();
  for (let i = 0; i < list.length; i++) {
    fd.append("swipers", list[i]);
    $.ajax({
      url: "/admin/swipers",
      type: "POST",
      data: fd,
      processData: false,
      contentType: false,
      success: function (res) {
        if (res.status === 0) {
          layer.msg(res.message);
          loadSwiper();
        }
      },
    });
  }
});